/**
 * 将扁平数组转换为树形结构
 * @param list 扁平数据数组
 * @param id 主键字段名
 * @param parentId 父级ID字段名
 * @param children 子节点字段名
 */
export function buildTree<T extends Record<string, any>>(list: T[], id = 'id', parentId = 'parentId', children = 'children'): T[] {
  const result: T[] = [];
  const map = new Map<number, T & Record<string, any>>();

  // 构建ID到对象的映射
  list.forEach(item => {
    map.set(item[id], {
      ...item,
      [children]: []
    });
  });

  // 构建树形结构
  list.forEach(item => {
    const currentItem = map.get(item[id])!;
    const parentItem = map.get(item[parentId]);

    if (parentItem) {
      parentItem[children].push(currentItem);
    } else {
      // parentId为0或不存在的项作为根节点
      result.push(currentItem);
    }
  });

  return result;
}

/**
 * 树形结构转扁平结构
 * @param tree 树形数据
 * @param children 子节点字段名
 */
export function flattenTree<T extends Record<string, any>>(tree: T[], children = 'children'): T[] {
  const result: T[] = [];

  const traverse = (nodes: T[]) => {
    nodes.forEach(node => {
      const { [children]: childNodes, ...rest } = node;
      result.push(rest as T);
      if (childNodes && childNodes.length > 0) {
        traverse(childNodes);
      }
    });
  };

  traverse(tree);
  return result;
}